import { router, addRoutes } from '@/router'
import { getToken } from '@/composables/auth.js'
import { totast } from './composables/until'
import { useUserStore } from '@/store'

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const token = getToken()
  const userStore = useUserStore()

  // 没有登录，强制跳转回登录页
  if (!token && to.path != '/login') {
    totast('请先登录', 'error')
    return next({ path: '/login' })
  }

  // 防止重复登录
  if (token && to.path == '/login') {
    totast('请勿重复登录', 'error')
    return next({ path: from.path ? from.path : '/' })
  }

  let title = (to.meta.title ? to.meta.title : '') + '-商城管理后台'
  document.title = title

  let hasNewRoutes = false
  if (token) {
    let { menus } = await userStore.getinfo()
    console.log(menus, 'ooooooooooo')

    hasNewRoutes = addRoutes(menus)
  }

  hasNewRoutes ? next(to.fullPath) : next()
})

// 后置
// router.afterEach((to, from) => )
